<?php

namespace app\api\service\intelligentlive;

use app\api\model\intelligentlive\Data;
use app\api\model\intelligentlive\Order;

class DataService
{
    private static $instance;

    public static function getInstance(): DataService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function setData($params)
    {
        $param = [
            "buyin_id" => $params["buyin_id"],
        ];
        $info = Data::where($param)->findOrEmpty();
        if (!empty($params["watch_sold_rate"])) {
            $params["watch_sold_rate"] = round($params["watch_sold_rate"], 4);
        }
        if ($info->isEmpty()) {
            Data::create($params);
        } else {
//            $newdata = [
////                "buyin_id" => $params["buyin_id"],
////                "nickname" => $params["nickname"],
//                "status" => $params["status"],
//                "pay_order_gmv" => $params["pay_order_gmv"],
//                "current_user_cnt" => $params["current_user_cnt"],
//                "watch_sold_rate" => $params["watch_sold_rate"],
//                "uv_value" => $params["uv_value"],
//                "new_fans_ucnt" => $params["new_fans_ucnt"],
//                "avg_watch_duration" => $params["avg_watch_duration"],
//            ];
            $info->save($params, ["id" => $info["id"]]);
        }
    }

    public function getData($params)
    {
        $pageSize = $params['pageSize']??200;
        $query = Data::field("*")->with(['account']);
        if (!empty($params["status"])) {
            $query->where("status", $params["status"]);
        }
        if (!empty($params["nickname"])) {
            $query->where('nickname',"like","%".$params['nickname']."%");
        }
        $data = $query->paginate($pageSize);

        //如果有条件 拼接id
        $ids = [];
        if (!$data->isEmpty() && (!empty($params["status"]) || !empty($params["nickname"]))) {
            foreach ($data as $key => $val) {
                $ids[$key] = $val["buyin_id"];
            }
        }

        //佣金
        $sql = Order::field("buyin_id, SUM(total_pay_amount) as gmv, SUM(total_commission) as money")
            ->whereBetweenTime("pay_time",$params["start_time"],$params["end_time"]);
        $totalsql = Order::field("SUM(total_pay_amount) as gmv, SUM(total_commission) as money")
            ->whereBetweenTime("pay_time",$params["start_time"],$params["end_time"]);
        if (!empty($ids)) {
            $sql->where("buyin_id", 'in', $ids);
            $totalsql->where("buyin_id", 'in', $ids);
        }

        $order_all = $sql->group("buyin_id")->select();
        $order_refund = $sql->where("order_status", 4)->group("buyin_id")->select();
        $all = $totalsql->select();
        $refund = $totalsql->where("order_status", 4)->select();

        $list = [];
        foreach ($order_all as $allitem) {
            $item["buyin_id"] = $allitem["buyin_id"];
            $item["gmv"] = $allitem["gmv"];
            $item["yxje"] = $allitem["gmv"];
            $item["money"] = $allitem["money"];
            foreach ($order_refund as $refunditem) {
                if ($allitem["buyin_id"] == $refunditem["buyin_id"]) {
                    $item["yxje"] = round($allitem["gmv"] - $refunditem["gmv"], 2);
                    $item["money"] = round($allitem["money"] - $refunditem["money"], 2);
                }
            }
            $list[] = $item;
        }

        foreach ($data as &$value) {
            foreach ($list as $val) {
                if ($value["buyin_id"] == $val["buyin_id"]) {
                    $value["gmv"] = $val["gmv"];
                    $value["yxje"] = $val["yxje"];
                    $value["money"] = $val["money"];
                }
            }
        }

        //统计
        $money = [
            "total" => [
                "gmv" => $all[0]["gmv"],
                "commission" => $all[0]["money"]
            ],
            "youxiao" => [
                "gmv" => round($all[0]["gmv"] - $refund[0]["gmv"], 2),
                "commission" => round($all[0]["money"] - $refund[0]["money"], 2)
            ],
            "refund" => [
                "gmv" => $refund[0]["gmv"],
                "commission" => $refund[0]["money"]
            ]
        ];

        $return = [
            "order" => $data,
            "money" => $money,
        ];

        return $return;
    }
}